import Taro from '@tarojs/taro'

import { IReqApi } from '@/api/core'
import { IResHeader, IResData } from './model'

// 更新用户授权登录
import { GetStorageToken, GetReqMethodAndPath, UpdateStorageToken, NoAuthorizationWillGoToWxLogin, PrintResLog, PrintReqLog } from './utils'

import MsgTips from '@/utils/msgTips'
import { HTTPSTATUS, CustomHttpStatusText } from './config'

/**
 * 自定义网络请求
 * @param url 请求地址  IReqApi
 * @param data 请求数据  any
 * @returns AbortTask function
 */
export default async function CustomFetch<T, U>(
  url: IReqApi,
  data?: T,
  token?: string,
): Promise<{ AbortTask: () => void; result: number; message: string; data: U; token?: string }> {
  try {
    const { authorization = '' } = GetStorageToken()

    const { method, url: reqUrl } = GetReqMethodAndPath(url)

    // 请求日志
    // PrintReqLog(reqUrl, data, method)
    // 请求数据
    const params = {
      url: reqUrl,
      method,
      data,
      ...(authorization ? { header: { ...GetStorageToken() } } : token ? { header: { authorization: token } } : {}),
    }
    const requestTask = Taro.request<IResData<U>>(params)
    const {
      statusCode,
      header,
      data: { result, message = '请求失败!', data: resData },
    } = await requestTask
    // 响应日志
    // PrintResLog(result, message, resData, reqUrl)
    // UpdateStorageToken(header as IResHeader)

    if (result === -1) {
      MsgTips(CustomHttpStatusText[result], { mask: true })
      NoAuthorizationWillGoToWxLogin()
      Taro.clearStorage()
    }

    if (statusCode !== HTTPSTATUS.SUCCESS) {
      MsgTips(CustomHttpStatusText[statusCode] || '未知错误!')
    }

    if (result !== HTTPSTATUS.RESULT) {
      MsgTips(CustomHttpStatusText[result] || message)
    }

    return {
      result: result,
      message: message,
      data: resData,
      token: header['authorization'] || header['Authorization'] || null,
      AbortTask: requestTask.abort,
    }
  } catch (err) {
    Taro.hideLoading()
    if ((err.errMsg as string).includes('timeout')) {
      MsgTips('请求超时!')
    }
    if ((err.errMag as string).includes('fail')) {
      MsgTips('请求失败!请检查网络')
    }
    return {
      reqTask: () => ({}),
      result: -9,
      message: '网络错误!',
      data: false,
    } as any
  }
}
